"""
Reusable helpers for working with the Neo4j driver.

This centralizes driver initialization so we only maintain a single connection
pool across the process and can add extra instrumentation later if needed.
"""

from functools import lru_cache
from typing import Optional

from django.conf import settings
from neo4j import GraphDatabase, basic_auth


def _build_auth_token() -> Optional[tuple]:
    if not settings.NEO4J_USER:
        return None
    return basic_auth(settings.NEO4J_USER, settings.NEO4J_PASSWORD or "")


@lru_cache(maxsize=1)
def get_neo4j_driver():
    """
    Lazily build a single driver instance.

    Using lru_cache avoids creating multiple connection pools when this helper
    is imported from different modules.
    """
    if not settings.NEO4J_URI:
        raise ValueError("NEO4J_URI is not configured")

    auth = _build_auth_token()
    driver = GraphDatabase.driver(settings.NEO4J_URI, auth=auth)
    return driver


def close_neo4j_driver():
    """
    Close the cached driver if it has been created.
    """
    cached_driver = get_neo4j_driver.cache_info().currsize
    if cached_driver:
        driver = get_neo4j_driver()
        driver.close()
        get_neo4j_driver.cache_clear()
